import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from generated_classes import create_connection, Users, UsersMapper, Departments, DepartmentsMapper, Products, ProductsMapper

"""
数据库测试套件

本测试套件验证所有生成的模型和 Mapper 类的功能。
测试包括：
1. 模型类的序列化和反序列化功能
2. Mapper 类的 CRUD 操作
3. 批量操作功能

数据库表说明：
- users 表：用户信息表
- departments 表：部门信息表
- products 表：产品信息表
"""

class TestModel:
    """模型类测试基类"""

    @staticmethod
    def test_serialization(model_class, test_data):
        """测试模型的序列化和反序列化功能"""
        print(f"\n测试 {model_class.__name__} 模型的序列化和反序列化功能...")

        # 创建模型对象
        model = model_class()
        for field, value in test_data.items():
            setattr(model, field, value)

        # 测试 to_dict 方法
        model_dict = model.to_dict()
        print(f"模型字典: {model_dict}")

        # 测试 to_json 方法
        model_json = model.to_json()
        print(f"模型JSON: {model_json}")

        # 测试 from_dict 方法
        model_from_dict = model_class.from_dict(model_dict)
        print(f"从字典创建的模型: {model_from_dict.__getattribute__(test_data[next(iter(test_data))].__class__.__name__ == 'str' and next(iter(test_data)) or 'name')}")

        # 测试 from_json 方法
        model_from_json = model_class.from_json(model_json)
        print(f"从JSON创建的模型: {model_from_json.__getattribute__(test_data[next(iter(test_data))].__class__.__name__ == 'str' and next(iter(test_data)) or 'name')}")

        print(f"{model_class.__name__} 模型测试通过！")
        return model

class TestMapper:
    """Mapper类测试基类"""

    @staticmethod
    def test_crud_operations(mapper_class, model_class, test_data):
        """测试 Mapper 类的 CRUD 操作"""
        print(f"\n测试 {mapper_class.__name__} 的 CRUD 操作...")

        # 创建数据库连接
        conn = create_connection()

        # 创建Mapper实例
        mapper = mapper_class(conn)

        # 创建模型对象
        model = model_class()
        for field, value in test_data.items():
            setattr(model, field, value)

        # 测试插入操作
        inserted_id = mapper.insert(model)
        print(f"插入的ID: {inserted_id}")

        # 测试查询操作
        if inserted_id:
            queried_model = mapper.get_by_id(inserted_id)
            if queried_model:
                print(f"查询到的记录: {queried_model.__getattribute__(test_data[next(iter(test_data))].__class__.__name__ == 'str' and next(iter(test_data)) or 'name')}")

                # 测试更新操作
                for field, value in test_data.items():
                    if field != 'id':
                        original_value = getattr(queried_model, field)
                        if isinstance(value, str):
                            # 对于字符串类型，检查是否是日期
                            if 'date' in field.lower():
                                from datetime import datetime
                                date_obj = datetime.strptime(value, '%Y-%m-%d')
                                new_date = datetime.strptime(f"2023-{date_obj.month}-{date_obj.day}", '%Y-%m-%d')
                                setattr(queried_model, field, new_date.strftime('%Y-%m-%d'))
                            else:
                                setattr(queried_model, field, f"新_{value}")
                        elif isinstance(value, int):
                            setattr(queried_model, field, original_value + 1)
                        elif isinstance(value, float):
                            # 处理 decimal 类型
                            from decimal import Decimal
                            if isinstance(original_value, Decimal):
                                setattr(queried_model, field, float(original_value) * 1.1)
                            else:
                                setattr(queried_model, field, original_value * 1.1)
                        else:
                            setattr(queried_model, field, value)

                mapper.update(queried_model)
                print("记录已更新")

                # 再次查询验证更新
                updated_model = mapper.get_by_id(inserted_id)
                print(f"更新后的记录: {updated_model.__getattribute__(test_data[next(iter(test_data))].__class__.__name__ == 'str' and next(iter(test_data)) or 'name')}")

                # 测试删除操作
                mapper.delete(inserted_id)
                print("记录已删除")

        # 关闭连接
        conn.close()
        print(f"{mapper_class.__name__} CRUD 操作测试通过！")

    @staticmethod
    def test_batch_operations(mapper_class, model_class, test_data, count=3):
        """测试 Mapper 类的批量操作"""
        print(f"\n测试 {mapper_class.__name__} 的批量操作...")

        # 创建数据库连接
        conn = create_connection()

        # 创建Mapper实例
        mapper = mapper_class(conn)

        # 创建多个模型对象
        models = []
        for i in range(count):
            model = model_class()
            for field, value in test_data.items():
                if isinstance(value, str):
                    setattr(model, field, f"{value}_{i}")
                elif isinstance(value, (int, float)):
                    setattr(model, field, value + i)
                else:
                    setattr(model, field, value)
            models.append(model)

        # 测试批量插入
        inserted_ids = mapper.batch_insert(models)
        print(f"批量插入的ID: {inserted_ids}")

        # 测试批量查询
        if inserted_ids:
            queried_models = mapper.get_by_ids(inserted_ids)
            print(f"批量查询到的记录数量: {len(queried_models)}")

            # 测试批量删除
            mapper.batch_delete(inserted_ids)
            print("批量删除完成")

        # 关闭连接
        conn.close()
        print(f"{mapper_class.__name__} 批量操作测试通过！")

def test_users_model():
    """测试用户模型类的序列化和反序列化功能"""
    test_data = {
        "username": "test_user",
        "email": "test@example.com",
        "age": 25,
        "comment": "测试用户"
    }
    TestModel.test_serialization(Users, test_data)

def test_users_crud():
    """测试用户Mapper类的CRUD操作"""
    test_data = {
        "username": "crud_test_user",
        "email": "crud_test@example.com",
        "age": 30,
        "comment": "CRUD测试用户"
    }
    TestMapper.test_crud_operations(UsersMapper, Users, test_data)

def test_departments_model():
    """测试部门模型类的序列化和反序列化功能"""
    test_data = {
        "name": "技术部",
        "manager": "张经理",
        "location": "科技园A座",
        "budget": 500000.00,
        "established_date": "2020-01-01"
    }
    TestModel.test_serialization(Departments, test_data)

def test_departments_crud():
    """测试部门Mapper类的CRUD操作"""
    test_data = {
        "name": "测试部门",
        "manager": "测试经理",
        "location": "测试地点",
        "budget": 100000.00,
        "established_date": "2023-01-01"
    }
    TestMapper.test_crud_operations(DepartmentsMapper, Departments, test_data)

def test_products_model():
    """测试产品模型类的序列化和反序列化功能"""
    test_data = {
        "name": "测试产品",
        "description": "这是一个测试产品",
        "price": 99.99,
        "stock_quantity": 100,
        "category": "电子产品"
    }
    TestModel.test_serialization(Products, test_data)

def test_products_crud():
    """测试产品Mapper类的CRUD操作"""
    test_data = {
        "name": "测试产品",
        "description": "这是一个测试产品",
        "price": 99.99,
        "stock_quantity": 100,
        "category": "电子产品"
    }
    TestMapper.test_crud_operations(ProductsMapper, Products, test_data)

def test_users_batch_operations():
    """测试用户Mapper类的批量操作"""
    test_data = {
        "username": "batch_test_user",
        "email": "batch_test@example.com",
        "age": 25,
        "comment": "批量测试用户"
    }
    TestMapper.test_batch_operations(UsersMapper, Users, test_data, count=3)

def test_departments_batch_operations():
    """测试部门Mapper类的批量操作"""
    test_data = {
        "name": "批量测试部门",
        "manager": "批量测试经理",
        "location": "批量测试地点",
        "budget": 100000.00,
        "established_date": "2023-01-01"
    }
    TestMapper.test_batch_operations(DepartmentsMapper, Departments, test_data, count=2)

def test_products_batch_operations():
    """测试产品Mapper类的批量操作"""
    test_data = {
        "name": "批量测试产品",
        "description": "这是一个批量测试产品",
        "price": 99.99,
        "stock_quantity": 100,
        "category": "电子产品"
    }
    TestMapper.test_batch_operations(ProductsMapper, Products, test_data, count=2)

def run_all_tests():
    """运行所有测试"""
    print("开始运行所有测试...")

    # 测试模型类的序列化和反序列化功能
    test_users_model()
    test_departments_model()
    test_products_model()

    # 测试Mapper类的CRUD操作
    test_users_crud()
    test_departments_crud()
    test_products_crud()

    # 测试批量操作
    test_users_batch_operations()
    test_departments_batch_operations()
    test_products_batch_operations()

    print("\n所有测试通过！")

if __name__ == "__main__":
    try:
        run_all_tests()
    except Exception as e:
        print(f"测试失败: {e}")
        import traceback
        traceback.print_exc()
